const { json } = require('express');
var express = require('express');
var router = express.Router();
const query = require('../bd/query')



const jwt=require('jsonwebtoken');//导入
global.secret="linjunyuan";//制作全局密钥






var CODE;//邮箱验证码

const {send} = require('../tool/email.js')//邮箱发送



// 登录
router.post('/user/login',function(req,res,next){
  var loginId=req.body.loginId;
  var loginPassword=req.body.loginPassword;
  var sql=`select * from user where loginId=${loginId}`
  let token
  query(sql)
  .then((resule)=>{ 
    // res.end(JSON.stringify(resule))
    if(resule.length>0)//有账户信息
    {
      token = 'Bearer'+jwt.sign(
        {loginId},
        global.secret,
        {expiresIn:3600*24}
      )
      res.send({
        status:"ok",
        token,
        resule,
      })
    }
    else
    {
      res.send({
          status:"no",
          token,
          resule,
        }
      )
    }
  
  
  })
  // res.end("访问到了")
})



// 注册
router.post('/user/register',function(req,res,next){
  var {loginId,loginPassword,mail,code}=req.body
  // console.log(mail)
  var adduser=`INSERT INTO user(loginId,loginPassword,email) VALUES (${loginId},"${loginPassword}","${mail}")`;
    console.log(adduser)
  query(adduser)
  .then((r)=>{
    console.log("成功")
    console.log(r.affectedRows)
    if(r.affectedRows==1){
      res.end(JSON.stringify({msg:"注册成功",status:"yes"}))
    }
    else{
      res.end(JSON.stringify({msg:"注册失败",status:"yes"}))
    }

  })
  .catch((r)=>{res.end(JSON.stringify({msg:"连接失败",status:"no"}))})
})
//忘记密码
router.post('/user/forgetPwd',function(req,res,next){
  var loginId=req.body.loginId;//账户id
  var loginPassword=req.body.loginPassword;//账户新密码
  var code=req.body.code;
  console.log(CODE,code)
  if(CODE!=code){
    res.end("验证码错误")
  }
  else{
    // let code = Math.random().toString().substr(2, 6)//随机取0~1之间小数点后6位
    var sql=`UPDATE user SET loginPassword=${loginPassword} where loginId=${loginId}`//查询账户
    query(sql)
    .then((resule)=>{
      console.log(resule)

      console.log(resule.affectedRows)
      if(resule.affectedRows==1){
        res.end('修改成功')
      }
      else{
        res.end('修改失败')
      }

    })

  }

})
// 获取注册验证码
router.post('/user/getRcode',(req,res)=>{
  var mail=req.body.mail
  console.log(mail)
  var Rcode = Math.random().toString().substr(2, 6)//随机取0~1之间小数点后6位
  CODE=Rcode,
  send(mail,Rcode,"源博客---注册账号")
  .then( (r)=>{  res.end(JSON.stringify({"status":"yes",r,"Rcode":Rcode}))})//发送验证码
  .catch( (r)=>{  res.end(JSON.stringify({"status":"no",r}))})
})

//修改个人信息
router.post('/user/setuser',(req,res)=>{
  var loginId = req.body.loginId  //登录id
  var loginPassword =req.body.loginPassword//获取密码
  var loginname = req.body.loginname  //网名
  var name = req.body.name  //姓名
  var age = req.body.age  //年龄
  var sex =req.body.sex //性别
  var email = req.body.email  //邮箱
  var signature = req.body.signature  //个性签名
  var sql=`UPDATE user SET loginname="${loginname}",
          name="${name}", age=${age} ,sex="${sex}",email="${email}",signature="${signature}"
          where loginId=${loginId} and loginPassword="${loginPassword}"` //查询账户
  query(sql)
  .then((resule)=>{
    console.log(resule)
    console.log(resule.affectedRows)
    if(resule.affectedRows==1)
    {
      res.end(JSON.stringify({status:"ok",msg:"修改成功"}))
    }
    else
    {
      res.end('修改失败')
    }
  })
  .catch(r=>{res.end({status:"no",msg:"修改失败"})})
})


//获取忘记密码验证码
router.post('/user/getcode',function(req,res,next){
  // var mail=req.body.mail;
  var loginId = req.body.loginId;
  var sql=`select email from user where loginId=${loginId}`//查询邮箱
  var mail;
  query(sql)
  .then((resule)=>{ return JSON.stringify(resule)  })
  .then((resule)=>{ 
    // console.log(resule)
    resule=JSON.parse(resule);
    if(resule.length==0){//判断账号错误
      res.end("账号错误")
    }
    else{
      mail=resule[0].email//获取邮箱
      console.log(mail)
      var code = Math.random().toString().substr(2, 6)//随机取0~1之间小数点后6位
      CODE=code,//全局code
      send(mail,code,"源博客---忘记密码").then( (r)=>{  res.end(JSON.stringify(r))})
      .catch( (r)=>{  res.end(JSON.stringify(r))})
    }
  })
  // .catch((resule)=>{
  //   res.end({msg:'获取邮箱验证码出错误拉'})
  //   // console.log('失败'+JSON.stringify(resule)) 
  // })
  // 715736015@qq.com
})
router.post('/user/setPassword',(req,res,next)=>{
  var loginId = req.body.loginId
  var oldPassword = req.body.oldpassword
  var newPassword = req.body.newpassword
  // var twoPassword = req.body.twoPassword
  var updatepassword=`update user set loginPassword = "${newPassword}" where loginId=${loginId} and loginPassword = ${oldPassword}`
  console.log(updatepassword)
  query(updatepassword)
  .then((r)=>{
    if(r.affectedRows==1){
      res.end(JSON.stringify({status:"ok",msg:"修改成功"}))
    }
    else{
      res.end(JSON.stringify({status:"no",msg:"修改失败"}))
    }
  })
  .catch(r=>{
    console.log(JSON.stringify({status:"no",msg:"连接失败"}))
  })
})

// const multer = require('multer')//头像上传插件
// const fs =require('fs')//文件操作插件
// const HeadImgupload = multer({ dest: '../public/headImg/' })	//头像存储路径
// /**
//  * 上传头像
//  */
// router.post('/media/heading',HeadImgupload.any,function(req, res, next) {
//   var headimg=req.files
//   console.log(123456789)
// console.log(req);
// res.end("在制作")
// });


module.exports = router;
